package com.hyt.it.ogt.kq.common.utils;

import cn.hutool.core.io.IoUtil;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;

/**
 * @author 刘恒活
 * @since 2021/4/21 9:09
 */
public class HttpUtil {
    public static void main(String[] args) {
        LocalDateTime c = LocalDateTime.now();
        System.out.println(c);
        System.out.println(c.plusMinutes(0));
    }

    public static InputStream getInputStreamFromUrl(String urlStr) {
        InputStream inputStream=null;
        try {
            //url解码
            URL url = new URL(urlStr);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            // 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
        } catch (IOException e) {

        }
        return inputStream;
    }

    public static void downFile(String url, String filePath) {
        BufferedInputStream bis = null;
        InputStream inputStream = null;
        BufferedOutputStream bos = null;
        try {
            // 建立链接
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(url);
            // 提交请求并以指定编码获取返回数据
            HttpResponse httpResponse = httpClient.execute(get);
            //获取网络输入流
            inputStream = httpResponse.getEntity().getContent();
            bis = new BufferedInputStream(inputStream);
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）

            bos = new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] buf = new byte[1024 * 1024];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            System.out.println("down end");
        } catch (Exception e) {
            throw new KqException();
        } finally {
            IoUtil.close(bos);
            IoUtil.close(inputStream);
            IoUtil.close(bis);
        }
    }
}
